<template>
	<div class="box">
		<!-- 头部搜索模块 -->
		<headerSearch 
      :selectObj="selectObject" 
      :goSearchFc="searchClick" 
      :buttonList="buttonList"
    />
		<!-- 中间表格模块 -->
    <BaseTable
        :data="cargotableData"
        :columns="cargotableDataColumns"
        :tableHeight="mainHeight"
        :pagination="false"
        :loading="loading"
        :Propsref="'ticketTable'"
        @details="tableClick"
        @checkId="checkTable"
        :onSelectChange="()=>{}"
        ref="baseTable"
    ></BaseTable>

		<div class="page">
			<el-pagination
				background
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryAll.startpage"
				:page-sizes="[10, 15, 20, 25, 30]"
				:page-size="queryAll.pagesize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalNum"
			></el-pagination>
		</div>
    <!-- 新建票货信息 -->
    <el-drawer
			:before-close="handleClose"
			title="新建票货信息"
			:visible.sync="ticketInfomation"
			direction="rtl"
      @open="openDrawer"
			size="50%"
		>
      <detail 
        ref="addDetail"
        :shipVoyageData="shipVoyageData"
        :compData="compData"
        :customerData="customerData"
        :cargoData="cargoData"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="addSave" size="mini" :loading="ineerLoading">
					{{ ineerLoading ? "提交中 ..." : "保 存" }}
				</el-button>
        <el-button size="mini" @click="ticketInfomation = false">取消</el-button>
			</div>
		</el-drawer>

		<!-- 货权转移 -->
		<el-drawer
			:before-close="handleClose"
			title="货权转移"
			:visible.sync="drawerInner"
			direction="rtl"
      @open="openDrawer"
			size="50%"
		>
      <cargoTransfer
        ref="cargoTransfer"
        :customerData="customerData"
      />
			<div class="demo-drawer__footer">
				<el-button type="primary" @click="cargoTransferSave" size="mini" :loading="ineerLoading">
					{{ ineerLoading ? "提交中 ..." : "保 存" }}
				</el-button>
        <el-button size="mini" @click="drawerInner = false">取消</el-button>
			</div>
		</el-drawer>

    <!-- 货权查询 -->
		<el-drawer
			:before-close="handleClose"
			title="货转查询"
			:visible.sync="cargoQuery"
			direction="rtl"
			size="50%"
		>
      <!-- 中间表格模块 -->
      <BaseTable
        :data="cargoTransferData"
        :columns="cargoTransferDataColumns"
        :tableHeight="tableHeight"
        :pagination="true"
        :loading="loading"
        @details="tableClick"
      ></BaseTable>
		</el-drawer>

    <!-- 货权转移附件查询 -->
    <el-dialog
      title="货权转移附件"
      :visible.sync="openFile"
      width="30%"
      :before-close="handleClose"
      append-to-body>
      <div 
        v-for="(item,index) in fileList" :key="item.fileId" 
        @click="handlePreview(item)"
        style="cursor:pointer;margin: 5px 0;"
      >{{index + 1}}、{{item.fileName}}
      </div>
      <el-empty description="未上传附件" v-if="fileList.length === 0"></el-empty>
      
    </el-dialog>

	</div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/Business/ticketsManage'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
import detail from './detail.vue'
import cargoTransfer from './cargoTransfer.vue'
import axios from 'axios'
import config from '@/network/config.js'
export default {
  name: 'ticketsManage', // 票货管理
  components: {
    BaseTable,
    headerSearch,
    detail,
    cargoTransfer
  },
  data() {
    return {
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageId',
          selectData: [],
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageId'
        },
        {
          name: '货主',
          type: 'select',
          modelName: 'cargoOwnerId',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '货代',
          type: 'select',
          modelName: 'cargoAgentId',
          selectData: [],
          selectLabel: 'customerName',
          selectValue: 'customerId'
        },
        {
          name: '货名',
          type: 'select',
          modelName: 'cargoCode',
          selectData: [],
          selectLabel: 'cargoName',
          selectValue: 'cargoCode'
        }
      ],
      // header的按钮list
      buttonList: [
        { label: '新建', type: 'primary', icon: 'el-icon-plus', vif: true, click: () => this.addTicketInfomation, disabled: false, permission: 'businessManagement:ticketsManage:add' },
        { label: '货权转移', type: 'primary', icon: '', vif: true, click: () => this.cargoManage, disabled: true, permission: 'businessManagement:ticketsManage:cargoOwnerTransfer' },
        { label: '货转查询', type: 'primary', icon: '', vif: true, click: () => this.openCargoQuery, disabled: true, permission: 'businessManagement:ticketsManage:queryTransferInfoList' }
      ],
      cargotableDataColumns: [ // table表头
        { type: 'selection' },
        { prop: 'companyName', label: '组织', isShort: true },
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'cargoOwnerName', label: '货主', isShort: true },
        { prop: 'cargoAgentName', label: '货代', isShort: true },
        { prop: 'cargoName', label: '货名' },
        { prop: 'tradeType', label: '贸别' },
        { prop: 'issuingCompanyName', label: '开证公司', isShort: true },
        { prop: 'packingName', label: '包装' },
        { prop: 'cargoRightsQuantity', label: '货权剩余量' }
      ],
      cargoTransferDataColumns: [ // table表头
        { prop: 'cargoOwnerNameSource', label: '源货主', isShort: true },
        { prop: 'cargoAgentNameSource', label: '源货代', isShort: true },
        { prop: 'cargoOwnerName', label: '目标货主', isShort: true },
        { prop: 'cargoAgentName', label: '目标货代', isShort: true },
        { prop: 'transferDate', label: '货转日期' },
        { prop: 'storageDate', label: '堆存费起算日期', width: 130 },
        { prop: 'quantity', label: '货转件数' },
        { prop: 'ton', label: '货转重量' },
        { prop: 'volume', label: '货转体积' },
        {
          label: '操作',
          fixed: 'right',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h(
              'div',

              [
                h('el-button', {
                  props: {
                    size: 'mini'
                  },

                  domProps: {
                    // 添加标签,使用自己引入的iconfont图标
                    innerHTML:
											"<span style='color:#0B6CD6'><i class='iconfont icon-1-07'></i><span  style='padding-left:5px;'>查看附件</span></span>"
                  },
                  on: {
                    click: () => {
                      this.viewFile(params.row)
                    }
                  }
                })
              ]
            )
          }
        }
      ],
      cargotableData: [], // table数据
      shipVoyageData: [], // 船名航次数据
      compData: [], // 组织数据
      customerData: [], // 货主货代开征公司数据
      cargoData: [], // 货名数据
      drawerInner: false, // 货权转移
      cargoFormData: { 'transferType': 2, 'id': '', 'mattachmentInfoList': [], 'cargoOwnerName': '', 'cargoAgentName': '', 'cargoInfoIdSource': '', 'cargoOwnerId': '', 'cargoAgentId': '', 'storageDate': '', 'transferDate': '', 'quantity': '', 'ton': '', 'volume': '', 'remark': '' }, // 货权转移内部初始form表单
      fileList: [], // 货转附件数据
      cargoQuery: false, // 货权查询
      cargoTransferData: [], // 货权查询数据
      ticketInfomation: false, // 新建票货信息
      addFormData: { 'companyId': '', 'companyName': '', 'shipvoyageName': '', 'cargoOwnerName': '', 'cargoAgentName': '', 'cargoName': '', 'tradeName': '', 'packingName': '', 'issuingCompanyName': '', 'shipvoyageId': '', 'cargoOwnerId': '', 'cargoAgentId': '', 'cargoCode': '', 'tradeType': '', 'packing': '', 'issuingCompanyId': '' }, // 新建表单初始form
      activeName: 'first',
      loading: false,
      clickRow: {}, // 点击行数据
      checkRow: [], // 选中行数据
      queryAll: {
        startpage: 1,
        pagesize: 10,
        portName: '',
        logogram: '',
        customerId: '',
        trustId: ''
      },
      totalNum: 0,
      drawerOut: false,
      flagOut: true,
      nationData: [], // 船籍
      flagIneer: true,

      openFile: false, // 查看附件
      portClassData: [],
      provinceData: [],
      cityData: [],
      oldOut: {},
      oldInner: {},
      outLoading: false,
      ineerLoading: false
    }
  },
  async mounted() {
    this.getCustomer()
    this.getComp()
    this.getCargo()
    this.getShipvoyage()
    if (this.customerId) {
      this.buttonList.map(item => {
        item.vif = false
        return item
      })
    }
  },
  props: {
    height: {
      type: Number
    },
    customerId: {
      type: String,
      default: ''
    },
    processCode: {
      type: String,
      default: ''
    },
    trustId: {
      type: String,
      default: ''
    }
  },
  computed: {
    mainHeight: function() {
      return this.height ? this.height : this.$store.state.tableHeight - 40
    },
    tableHeight: function() {
      return this.$store.state.tableHeight - 40
    }
  },
  methods: {
    /**
     * 获取票货数据
     */
    async getTickList() {
      this.queryAll.customerId = this.customerId
      this.queryAll.processCode = this.processCode
      this.queryAll.trustId = this.trustId
      this.loading = true
      await api
        .reqGetTickets(this.queryAll)
        .then(res => {
          this.loading = false
          this.buttonList[1].disabled = true
          this.buttonList[2].disabled = true
          this.cargotableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.totalNum = res.data.data.totalNum
        })
        .catch(() => {})
    },
    /**
     * 新建票货信息
     */
    addTicketInfomation() {
      this.ticketInfomation = true
    },
    /**
     * 新建票货信息保存
     */
    async addSave() {
      const params = this.$refs.addDetail.formData
      this.$refs.addDetail.$refs.ruleForm.validate((valid) => {
        if (valid) {
          api.reqAddTickets(params).then(res => {
            if (res.data.code === '0000') {
              this.ticketInfomation = false
              this.$message.success('新建成功')
              this.getTickList()
              this.$refs.addDetail.$refs.ruleForm.resetFields()
            }
          })
        } else {
          this.$message.warning('请完善表单')
          return false;
        }
      });
    },
    /**
     * 表格点击事件，拿到row的id
     */
    tableClick(row) {
      this.clickRow = row
      this.buttonList[1].disabled = false
      this.buttonList[2].disabled = false
    },
    /**
     *
     */
    checkTable(val) {
      this.checkRow = val
      console.log(val, 'val');
    },
    /**
     * 打开货权转移抽屉
     */
    cargoManage() {
      this.drawerInner = true
      this.$nextTick(() => {
        // 将id和对应字段填进去
        this.$refs.cargoTransfer.formData.cargoInfoIdSource = this.clickRow.id
        this.$refs.cargoTransfer.yph = this.clickRow.cargoOwnerName + '/' + this.clickRow.cargoAgentName + '/' + this.clickRow.cargoName + '/' + this.clickRow.tradeType + '/' + this.clickRow.shipvoyageName
      })
    },
    /**
     * 货权转移保存
     */
    async cargoTransferSave() {
      const params = this.$refs.cargoTransfer.formData

      this.$refs.cargoTransfer.$refs.ruleForm.validate((valid) => {
        if (valid) {
          api.reqSaveCargo(params).then(res => {
            if (res.data.code === '0000') {
              this.drawerInner = false
              this.buttonList[1].disabled = true
              this.buttonList[2].disabled = true
              this.$message.success('货权转移成功')
              for (const key in params) {
                params[key] = ''
              }
              this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
              this.getTickList()
            }
          })
        } else {
          this.$message.warning('请完善表单数据')
          return false;
        }
      });
    },
    /**
     * 打开货权查询抽屉
     */
    openCargoQuery() {
      this.cargoQuery = true
      this.getCargoList()
    },
    /**
     * 获取货权查询信息
     */
    async getCargoList() {
      const params = { cargoInfoIdSource: this.clickRow.id }
      const res = await api.reqGetCargo(params)
      this.cargoTransferData = res.data.data
    },
    /**
     * 货权查询中查看附件
     */
    viewFile(row) {
      this.openFile = true
      console.log(row, 'row');
      this.fileList = row.mattachmentInfoList
    },
    /**
     * 预览附件
     */
    handlePreview(file) {
      console.log(file);
      if (file.fileName.indexOf('jpg') !== -1 || file.fileName.indexOf('png') !== -1 || file.fileName.indexOf('jpeg') !== -1) {
        axios({
          method: 'get',
          url: `${config.ConfigBaseURL}/wfpms-master-service/api/external/publics/file/down?id=${file.fileId}`,
          responseType: 'arraybuffer',
          params: {
            token: window.sessionStorage.getItem('token')
          }
        }).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/png;charset=utf-8'
          });
          const url = window.URL.createObjectURL(blob);
          this.imgurl = url
          this.dialogVisible = true
        })
      } else {
        this.downLoadFile(file)
      }
    },
    /**
     * 下载附件
     */
    async downLoadFile(file) {
      const res = await publicapi.down(file.fileId)
      const content = res.data
      const blob = new Blob([content]) // 构造一个blob对象来处理数据
      const link = document.createElement('a') // 创建a标签
      link.download = file.fileName // a标签添加属性
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob, {
        type: `application/pdf`
      })
      document.body.appendChild(link)
      link.click() // 执行下载
      URL.revokeObjectURL(link.href) // 释放url
      document.body.removeChild(link) // 释放标签
    },
    /**
     * 获取客户信息，货主货代开征公司
     */
    async getCustomer() {
      const res = await publicapi.getlistCustomer()
      this.customerData = res.data.data
      this.selectObject[1].selectData = this.customerData
      this.selectObject[2].selectData = this.customerData
    },
    /**
     * 获取组织
     */
    async getComp() {
      const res = await publicapi.getListComp()
      this.compData = res.data.data
    },
    /**
     * 获取货名信息
     */
    async getCargo() {
      const res = await publicapi.getListCargo()
      this.cargoData = res.data.data
      this.selectObject[3].selectData = this.cargoData
    },
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    searchClick(searchData) {
      console.log(searchData, 'searchData');
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.getTickList()
    },

    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getTickList()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getTickList()
    },
    /**
     * 打开抽屉的回调,将对应抽屉的form表单清空
     */
    openDrawer() {
      if (this.drawerInner) { // 货权转移
        this.$nextTick(() => {
          this.$refs.cargoTransfer.$refs.ruleForm.resetFields()
          this.$refs.cargoTransfer.formData.mattachmentInfoList = []
        })
      } else if (this.ticketInfomation) { // 新增
        this.$nextTick(() => {
          this.$refs.addDetail.$refs.ruleForm.resetFields()
        })
      }
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerInner) {
        oldV = this.cargoFormData
        newV = this.$refs.cargoTransfer.formData
      }
      if (this.ticketInfomation) {
        oldV = this.addFormData
        newV = this.$refs.addDetail.formData
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => {})
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "~@/assets/form.less";

.selectBox {
	justify-content: space-between;
	display: flex;
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-bottom: 0;
	border-left: none;
	height: 50px;
	position: relative;
	align-items: center;
	padding-left: 14px;
	padding-right: 20px;
}
.input_box {
	display: flex;
}
.page {
	background: #ffffff;
	text-align: right;
	border-radius: 0 0 4px 4px;
	padding: 5px 20px;
}
/deep/.el-tabs--border-card > .el-tabs__content {
	padding: 0 !important;
}
//抽屉底部样式
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 16px;
	border-bottom: 1px solid gainsboro;
}
.demo-drawer__footer {
	text-align: right;
	padding-right: 20px;
	border-top: 1px solid #c8cfde;
	background-color: #f5f7fa;
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	line-height: 50px;
}
.box {
	background: #ffffff;
	border: 1px solid #e1e4eb;
	border-radius: 4px 4px 0 0;
	border-top: none;
}
</style>
